<template>
	<!-- 自定义导航栏 -->
	<CustomNavBar title="聊天室,在这里可以选择朋友进行聊天"/>

		<up-empty text="当前无在线用户"
			icon="http://cdn.uviewui.com/uview/empty/data.png">
		</up-empty>
		<up-cell-group v-for="user in userList">
			<up-cell       :title="user.userAccount"
      :icon="user.avatarUrl"
      @click="doChatUser(user.userAccount, messages)"
      is-link>
	  <template #right-icon  style="position: relative; display: inline-block;">
				<up-icon name="weixin-fill" color="green"
	  	          size="50rpx"
	  	          ></up-icon>
				    <view
				      v-if="messages.length >=0"
				      style="position: absolute; top: -12rpx; right: -5rpx; background: red; color: white; font-size: 20rpx; border-radius: 50%; width: 30rpx; height: 30rpx; display: flex; align-items: center; justify-content: center;"
				    >
				      {{ messages.length }}
				    </view>
	  </template>
	  </up-cell>
		</up-cell-group>
</template>

<script setup lang="ts">
import CustomNavBar from '@/components/CustomNavBar.vue';
import { onMounted, ref } from 'vue'
import { getCurrentUser } from '@/services/user'
import { myWebSocket } from '@/config/myWebSocket'

const user = ref('')
const socket = ref()
const messages = ref([])
const chatUser = ref('')
const content = ref('')
const userList = ref([
])

/**
 * 初始化
 */
onMounted(async () => {
  user.value = await getCurrentUser()
  init()
})

const init = () => {
  //获取用户账号作为聊天地址的参数
  console.log('user', user.value.userAccount)
  let userAccount = user.value.userAccount
  if (typeof WebSocket === 'undefined') {
    uni.showFailToast('浏览器不支持WebSocket')
  } else {
    uni.showSuccessToast('浏览器支持')
    let socketUrl = myWebSocket.url + userAccount
    socket.value = new WebSocket(socketUrl)
    socket.value.onopen = () => {
      console.log('WebSocket连接成功')
    }
    socket.value.onmessage = (msg: any) => {
      let data = JSON.parse(msg.data)
      console.log('data', data)
      if (data.userList) {
        userList.value = data.userList.filter(
          user => user.userAccount !== userAccount
        )
        console.log('在线用户列表', userList.value)
      } else {
        //如果data中没有userList代表这是一个信息,信息中有接收者的userAccount
        if (data.consumer === userAccount) {
          messages.value.push(data)
        }
      }
    }
  }
}

/**
 * 选择聊天的用户
 */
const doChatUser = (userAccount, messages) => {
  chatUser.value = userAccount;
  uni.navigateTo({
    url: `/pages/chat/info?userAccount=${encodeURIComponent(userAccount)}`
  });
};

</script>

<style scoped></style>
